package top.malaoshi.netdisk.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.malaoshi.jdbc.Record;
import top.malaoshi.netdisk.vo.JsonCodeMsg;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.netdisk.vo.ModifyPassword;
import top.malaoshi.sprout.jdbc.DbTemplate;
import top.malaoshi.util.Out;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.sql.SQLException;
import java.util.List;

@Service
public class UserSrvImpl {

    @Resource
    private DbTemplate dbTemplate;

    /**
     * 修改密码
     * @param modifyPassword
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult modifyPassword(ModifyPassword modifyPassword) throws SQLException {
        String valSQL = "select count(1) from t_user where uid = #{uid} and password = #{oldPassword}";
        List<Record> records = dbTemplate.queryTag(valSQL, modifyPassword);
        int count = 0;
        if(records != null && !records.isEmpty()){
            Record record = records.get(0);
            count = record.getIntValue(0);
        }

        if(count == 0){
            return JsonResult.fail(JsonCodeMsg.OPERATE_FAIL.getCode(), "原密码错误！");
        }
        String sql = "update t_user set password = #{newPassword} where uid = #{uid}";
        int i = dbTemplate.updateTag(sql, modifyPassword);
        if(i>0){
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail(JsonCodeMsg.OPERATE_FAIL.getCode(),"修改密码失败！" );
    }
}
